package com.sml.aop.cat;

import com.dianping.cat.Cat;
import com.dianping.cat.message.Transaction;
import java.lang.reflect.Method;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

@Aspect
public class CatMethodAspect {

  @Around(value = "@annotation(CatMethodAnnotation)")
  public Object aroundMethod(ProceedingJoinPoint pjp) throws Throwable {
    MethodSignature joinPointObject = (MethodSignature) pjp.getSignature();
    Method method = joinPointObject.getMethod();
    Transaction t = Cat.newTransaction("method", method.getName());
    // 统计接口被调用次数
    Cat.logMetricForCount(method.getName(), 1);
    try {
      Object res = pjp.proceed();
      t.setSuccessStatus();
      return res;
    } catch (Throwable e) {
      t.setStatus(e);
      Cat.logError(e);
      throw e;
    } finally {
      t.complete();
    }
  }

}
